<?php
/**
 * @Name: UtilImg.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace HugCode\PhpUnits\Utils;

class UtilImg
{

    /**
     * @Desc 下载远程图片
     * @param string $url 图片链接
     * @param string $filename 保存地址
     * @return string[]
     * @throws \Exception
     * @author yashuai<1762910894@qq.com>
     */
    public function downloadImg(string $url, string $filename)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        $file  = curl_exec($ch);
        $code  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = $file === false ? curl_error($ch) : false;
        curl_close($ch);
        if (!empty($error)) throw new \Exception($error);

        if ($code === 200) {
            $this->savePicture($file, $filename);
            return ['path' => $filename];
        } else {
            throw new \Exception('request error code: ' . $code);
        }
    }

    /**
     * @Desc 保存图片
     * @param $file
     * @param string $filename 保存地址
     * @return string
     * @author yashuai<1762910894@qq.com>
     */
    public function savePicture($file, string $filename)
    {
        $dirname = pathinfo($filename, PATHINFO_DIRNAME);
        UtilFile::mkdir($dirname);
        $resource = fopen($filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $filename;
    }

    /**
     * @Desc 图片url转base64
     * @param string $url
     * @return string
     * @throws \Exception
     * @author yashuai<1762910894@qq.com>
     */
    public static function imgUrlToBase64(string $url = '')
    {
        try {
            $imageInfo           = getimagesize($url);
            $mime                = UtilArray::arrayField($imageInfo, 'mime', 'jpg');
            $imageInfo['base64'] = base64_encode(file_get_contents($url));
            $imageInfo['mime_data']   = 'data:' . $mime . ';base64,';

            $type              = [
                1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'swf', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff',
                9 => 'jpc', 10 => 'jp2', 11 => 'jpx', 12 => 'jb2', 13 => 'swc', 14 => 'iff', 15 => 'wbmp', 16 => 'xbm'
            ];
            $imageInfo['type'] = $type[$imageInfo[2]] ?? '';
            return $imageInfo;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * @Desc base64保存图片
     * @param string $base64
     * @param string $rootPath
     * @param string $fileDir
     * @param bool $fileName
     * @return bool|string
     * @author yashuai<1762910894@qq.com>
     */
    public static function base64ToImg(string $base64, string $rootPath = '/', string $fileDir = '/', bool $fileName = false)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
            UtilFile::mkdir($rootPath . $fileDir);
            $fileName    = $fileName ? $fileName : UtilString::randomString(32) . '.' . $result[2];
            $filePath    = $fileDir . $fileName;
            $fileContent = base64_decode(str_replace($result[1], '', $base64));
            if (file_put_contents($rootPath . $filePath, $fileContent)) {
                return $filePath;
            }
            return false;
        }
        return false;
    }

}
